var express = require("express");
var multer = require("multer");

//这个方式能上传文件，但是文件名可读性差，没有后缀，优点：目录无则自动创建
// var upload = multer({ dest: "uploads/" });

var app = express();
//设置文件存储位置和文件命名
var storage = multer.diskStorage({
  //   destination: function (req, file, cb) {
  //     //目录不会自动创建
  //     cb(null, "uploads/");
  //   },
  destination: "uploads/", //目录无则自动创建
  filename: function (req, file, cb) {
    // console.log(file, 999);
    let filename = file.originalname; //wzj.jpg
    let arr = filename.split("."); //['wzj','jpg']
    // cb(null, file.fieldname + "-" + Date.now());
    cb(null, arr[0] + "-" + Date.now() + "." + arr[1]);
  },
});

var upload = multer({ storage: storage });

//上传单个文件
app.post("/headpic", upload.single("avatar"), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
  console.log(req.file, 999); //存储文件相关数据
  //   console.log(__dirname, 899); //http://localhost:3001/uploads/wzj-1601001498746.jpg
  //   console.log(req.body); //存储文件之外的数据
  let str = req.file.path.replace(/\\/, "/");
  //   console.log(str, 666);
  let url = "http://localhost:3001/" + str;
  console.log(req.file.path, 888);
  console.log(url, 777);
  res.send(url);
});

//上传多个文件
app.post("/goodpic", upload.array("photos", 5), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
  console.log(req.files, 999); //存储文件相关数据：数组
  console.log(req.body); //存储文件之外的数据
  res.send("888");
});

//开启静态资源服务器
app.use(express.static("./"));

//开启服务 端口号：1000-60000
app.listen(3001, () => {
  console.log("服务器已开启，请访问：http://localhost:3001");
});
